<?php


namespace app\api\model;

use think\Model;

/**
 *   帖子模型
 *
 *
 * Class Posts
 * @package app\api\model
 */
class Posts extends Model
{
    /**
     * 获取帖子是否为收费帖子
     *
     * @param $value
     * @return string
     */
    // public function getFreeAttr($value)
    // {
    //     $status = [1 => '免费内容', 2 => '付费内容'];
    //
    //     return $status[$value];
    // }
    /**
     * 帖子关联评论表
     *
     * @return \think\model\relation\HasOne
     */
    public function comments()
    {
        return $this->hasMany('app\api\model\Comments', 'post_id', 'id');
    }

    /**
     * 帖子关联圈子表
     *
     * @return \think\model\relation\HasOne
     */
    public function circle()
    {
        return $this->hasMany('app\api\model\Circle', 'id', 'circle_id');
    }

    /**
     * 帖子关联用户表
     *
     * @return \think\model\relation\HasOne
     */
    public function user()
    {
        return $this->hasMany('app\api\model\User', 'id', 'user_id');
        // return $this->hasOne('User', 'id', 'user_id');
        // return $this->hasOne('User', 'posts_id', 'id');
    }

    /**
     * 获取推荐帖子
     *
     */
    public function recPosts()
    {
        $list = $this->with('user,circle')->where('recommend', 1)->select();
        return $list;
    }

    /**
     * 获取指定圈子下的所有帖子
     *
     */
    public function getcPost($circle_id)
    {
        $posts = $this->with('user')->where('circle_id', $circle_id)->select();
        return $posts;
    }

    /**
     * 获取搜索帖子
     *
     */
    public function searchPost($data)
    {
        $posts = $this->where('title | content', 'like', "%" . $data . "%")->select();
        return $posts;
    }

    /**
     * 获取帖子详情
     *
     */
    public function detail($id)
    {
        $posts = Posts::where('id', $id)->with('comments,circle,user')->find()->toArray();
        // return $posts;

        foreach ($posts['comments'] as $key => $value) {
            $user_id = $value['user_id'];
            $userinfos = User::where('id', $user_id)->field('nick_name,headimgurl')->find()->toArray();
            //将评论用户的姓名查出后重新赋值到评论分组下
            $posts['comments'][$key]['nickname'] = $userinfos['nick_name'];
            $posts['comments'][$key]['img'] = $userinfos['headimgurl'];
        }
        if ($posts['free'] == 2) {
            return '这是付费帖子';
        }
        return $posts;
    }

    /**
     * 发送新帖子
     *
     */
    public function sendPost($data)
    {
        $circle = Circle::field('id')->select();
        foreach ($circle as $value) {
            $ids = $value['id'];
            $data['circle_id'] = $ids;
        }
        $res = $this->insert($data);
        return $res;
    }
}